﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace KinectedMusic.Audio
{
    class SongControl
    {
        private Song song;
        private AudioOut audioOut;
        private double position;
        private double barStep;

        public int BufferSize
        {
            get
            {
                return audioOut.BufferSize;
            }
        }

        public SongControl(Song song)
        {
            this.song = song;
            audioOut = new AudioOut(this);
            //TODO: Should I load vst when I add it?
            //song.LoadVSTs(audioOut.BufferSize);
            position = 0;
            barStep = CalculateBarStep(song.BeatsPerMinute, song.BeatsPerBar, audioOut.BufferSize, audioOut.SampleRate);
        }

        public void StartSong()
        {
            audioOut.StartDriver();
        }

        public void StopSong()
        {
            position = 0;
            audioOut.StopDriver();
        }


        //public IInstrument AddInstrument(string pluginName)
        //{
        //    return song.AddInstrument(pluginName);
        //}

        private double CalculateBarStep(double beatsPerMinute, int beatsPerBar, int bufferSize, double sampleRate)
        {
            double timeStep = bufferSize / sampleRate;
            double barsPerMinute = beatsPerMinute / beatsPerBar;
            double timeForBar = 60.0 / barsPerMinute;
            return timeStep / timeForBar;
        }

        public List<Jacobi.Vst.Core.VstAudioBuffer[]> GetOutputBuffers()
        {
            List<Jacobi.Vst.Core.VstAudioBuffer[]> outputBuffers = song.GetOutputBuffers(position, barStep, audioOut.BufferSize);
            position += barStep;
            return outputBuffers;
        }


    }
}
